package cn.aaalei.shorturl.aspect;

import cn.hutool.extra.servlet.ServletUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

@Aspect
@Component
public class WebLogAspect {

    private RestTemplate restTemplate = new RestTemplate();

    @Autowired
    private RabbitTemplate rabbitTemplate;

    private Long beginTime;

    @Pointcut("execution(* cn.aaalei.shorturl.controller.ResolveController.*(..))")
    public void logPointCut(){}

    @Before("logPointCut()")
    public void doBefore(JoinPoint joinPoint) throws Throwable{
        System.out.println("PointCutBefore");
        beginTime = System.currentTimeMillis();

        //AOP中实现 太耗费时间 改用消息队列

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String createTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        String messageIPAddress = ServletUtil.getClientIP(request);
        String messageData = ServletUtil.getHeader(request, "User-Agent", "UTF-8");

        Map<String,Object> map=new HashMap<>();
        map.put("createTime",createTime);
        map.put("messageIPAddress",messageIPAddress);
        map.put("messageData",messageData);
        map.put("messageShort",request.getRequestURI().substring(1));
        //将消息携带绑定键值：TestDirectRouting 发送到交换机TestDirectExchange
        rabbitTemplate.convertAndSend("WebLogDirectExchange", "WebLogDirectRouting", map);
    }

    @After("logPointCut()")
    public void doAfter(JoinPoint joinPoint) throws Throwable {
        System.out.println("PointCutAfter");
        Long afterTime = System.currentTimeMillis();
        System.out.println("总耗时:" + (afterTime - beginTime) + "ms");
    }
}
